package com.whzykj.common.wx;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class PayUtil {

	/******
	 * 商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易回话标识后再在APP里面调起支付。
	 * @param order_id
	 * @param balance_pay
	 * @param money
	 * @param openid
	 * @param nonce_str
	 * @param ip
	 * @return
	 */
	public static Map<String,String> unifiedorder(String order_id,String balance_pay,BigDecimal money,String nonce_str,String ip,String user_id){
		HttpRequestor http =new HttpRequestor();
		//余额支付
		if(balance_pay == null || "".equals(balance_pay))
		{
			balance_pay="0";
		}
		BigDecimal balancepay=new BigDecimal(balance_pay);
		BigDecimal balance = money.subtract(balancepay);//减去支付金额后剩余余额
		BigDecimal moneyd = balance.multiply(new BigDecimal(100));
		int total_fee = moneyd.intValue();
		SortedMap<String,Object> parameterMap = new TreeMap<String, Object>();
		
		parameterMap.put("appid", WxConst.appid);
		parameterMap.put("mch_id", WxConst.mch_id);
		parameterMap.put("nonce_str", nonce_str);
		parameterMap.put("body", "百菜园订单支付");
		parameterMap.put("out_trade_no",order_id);
		parameterMap.put("total_fee", total_fee+"");
		parameterMap.put("spbill_create_ip", ip);
		parameterMap.put("notify_url", WxConst.pay_notify_url);
		parameterMap.put("trade_type", "APP");
		parameterMap.put("detail", createGoods(order_id));
		parameterMap.put("attach", user_id+"|"+balance_pay);
		parameterMap.put("sign", createSign("UTF-8", parameterMap));
		parameterMap.remove("key");
		
		String xml = Map2Xml.getRequestXml(parameterMap);
		try {
			System.out.println("生成预支付订单");
			System.out.println("回调地址："+WxConst.pay_notify_url);
			String str =http.post("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
			System.out.println("反馈:"+str);
			return XMLUtil.doXMLParse(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	/******
	 * 微信余额充值
	 * @param order_id
	 * @param balance_pay
	 * @param nonce_str
	 * @param ip
	 * @return
	 */
	public static Map<String,String> unifiedorder(String order_id,BigDecimal balance_pay,String nonce_str,String ip){
		HttpRequestor http =new HttpRequestor();
		
		BigDecimal moneyd = balance_pay.multiply(new BigDecimal(100));
		int total_fee = moneyd.intValue();
		
		SortedMap<String,Object> parameterMap = new TreeMap<String, Object>();
		
		parameterMap.put("appid", WxConst.appid);
		parameterMap.put("mch_id", WxConst.mch_id);
		parameterMap.put("nonce_str", nonce_str);
		parameterMap.put("body", "百菜园充值");
		parameterMap.put("out_trade_no",order_id);
		parameterMap.put("total_fee", total_fee+"");
		parameterMap.put("spbill_create_ip", ip);
		parameterMap.put("notify_url", WxConst.balancepay_notify_url);
		parameterMap.put("trade_type", "APP");
		parameterMap.put("detail", "");
		parameterMap.put("attach", "");
		parameterMap.put("sign", createSign("UTF-8", parameterMap));
		parameterMap.remove("key");
		
		String xml = Map2Xml.getRequestXml(parameterMap);
		try {
			System.out.println("生成预支付订单");
			System.out.println("回调地址："+WxConst.balancepay_notify_url);
			String str =http.post("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
			System.out.println("反馈:"+str);
			return XMLUtil.doXMLParse(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String createGoods(String orderid){
		Map<String,Object> map = new HashMap<String,Object>();
		List<Map<String,Object>> gList = new ArrayList<Map<String,Object>>();
		
		String sql=" SELECT g.goods_id,g.APP_NAME,o.SALE_PRICE,o.SALE_NUM FROM orderdetails o,goodsinfo g WHERE o.GOODS_ID=g.GOODS_ID AND o.ORDER_ID=? ";
		List<Record> list = Db.find(sql, orderid);
		for(Record rd : list)
		{
			Map<String,Object> good = new HashMap<String,Object>();
			
			int goods_id = rd.getInt("goods_id");
			String app_name = rd.getStr("app_name");
			BigDecimal sale_price = rd.getBigDecimal("sale_price");
			int sale_num = rd.getInt("sale_num");
			
			good.put("goods_id", goods_id);
			good.put("goods_name", app_name);
			good.put("quantity", sale_num);
			good.put("price", sale_price.multiply(new BigDecimal(100)).toString());
			//good.put("wxpay_goods_id", "match_session_id");
			//good.put("goods_category", "match_session_id");
			//good.put("body", "match_session_id");
			gList.add(good);
		}
		map.put("goods_detail", gList);
		return JSON.toJSONString(map);
	}
	
	 //随机字符串生成  
    public static String getRandomString(int length) { //length表示生成字符串的长度      
           String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";         
           Random random = new Random();         
           StringBuffer sb = new StringBuffer();         
           for (int i = 0; i < length; i++) {         
               int number = random.nextInt(base.length());         
               sb.append(base.charAt(number));         
           }         
           return sb.toString();         
        }    
	
    //生成签名  
    public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){  
          StringBuffer sb = new StringBuffer();  
          Set es = parameters.entrySet();  
          Iterator it = es.iterator();  
          while(it.hasNext()) {  
              Map.Entry entry = (Map.Entry)it.next();  
              String k = (String)entry.getKey();  
              Object v = entry.getValue();  
              if(null != v && !"".equals(v)  
                      && !"sign".equals(k) && !"key".equals(k)) {  
                  sb.append(k + "=" + v + "&");  
              }  
          }  
          sb.append("key=" + WxConst.api_key);  
          String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
          return sign;  
      } 
}
